import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.provider.MediaStore
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.newproject_overseas.ViewModel.ImageViewModel
import com.example.newproject_overseas.util.imageUtil.GlideEngine
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnCallbackListener
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.utils.ToastUtils
import org.json.JSONObject
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date
import java.util.Locale



// 获得照片信息
fun getPicture( context: Context,param: JSONObject,oper:Int){

    var imgImageViewModel = ViewModelProvider(context as ViewModelStoreOwner).get(ImageViewModel::class.java)

    val quality           = param.optInt("quality", 90)
    val encodingType      = param.optString("encodingType","jpg")
    val targetWidth       = param.optInt("targetWidth", 0)
    val targetHeight      = param.optInt("targetHeight", 0)
    val saveToPhotoAlbum  = param.optBoolean("saveToPhotoAlbum", false)
    val destinationType   = param.optString("destinationType","url")
    val maxImagesCount    = param.optInt("maxImagesCount", 1)
    val mediaValue        = param.optString("mediaValue","pic")

    val mimeType = if (mediaValue == "pic") {
        SelectMimeType.ofAll()
    } else {
        SelectMimeType.ofVideo()
    }


    val glideEngine: GlideEngine = GlideEngine.createGlideEngine();
    val pictureSelector = PictureSelector.create(context)
        .openGallery(mimeType)
        .setImageEngine(glideEngine) // 这里就是设置图片加载引擎
        .setMaxSelectNum(maxImagesCount)
        .setLanguage(LanguageConfig.ENGLISH)

    pictureSelector.forResult(object : OnResultCallbackListener<LocalMedia> {
        override fun onResult(result: ArrayList<LocalMedia>?) {

            result?.forEach { localMedia ->
                localMedia.apply {
                    // Get the path of the selected image
                    val imageUri = if (isCompressed) Uri.parse(compressPath) else Uri.parse(path)

                    glideEngine.loadImageBitmap(
                        context = context,
                        url = imageUri.toString(),
                        maxWidth = targetWidth,  // Replace targetWidth with the actual desired maximum width
                        maxHeight = targetHeight,  // Replace targetHeight with the actual desired maximum height
                        call = object : OnCallbackListener<Bitmap> {
                            override fun onCall(result: Bitmap?) {
                                result?.let { bitmap ->
                                    val baos = ByteArrayOutputStream()
                                    val currentDate = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(
                                        Date()
                                    )
                                    var title = "Image_$currentDate"
                                    val description = "Compressed image $currentDate"

                                    if (saveToPhotoAlbum) {
                                        val savedImageUri = MediaStore.Images.Media.insertImage(
                                            context.contentResolver,
                                            bitmap,
                                            title,
                                            description
                                        )
                                        // savedImageUri contains the URI of the saved image in the system album
                                    }

                                    if (encodingType.uppercase() == "JPG") {
                                        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos)
                                        title += ".jpg"
                                    } else {
                                        bitmap.compress(Bitmap.CompressFormat.PNG, quality, baos)
                                        title += ".png"
                                    }

                                    // Convert the compressed image to a file
                                    val file = File(context.getExternalFilesDir(null), title)
                                    val fos = FileOutputStream(file)
                                    fos.write(baos.toByteArray())
                                    fos.flush()
                                    fos.close()

                                    val filePath = file.absolutePath
                                    imgImageViewModel.loadImageBitmapFromFile(filePath,oper)
                                }
                            }
                        }
                    )
                }
            }

        }

        override fun onCancel() {
            // 取消拍照或选择图片
            ToastUtils.showToast(context, "Cancel the photo or select a picture")
        }
    })

}

